<template>
  <div class="container">
    <!-- <h1>会员</h1> -->
    <div class="handle-box">
      <el-button-group class="ml-4">
        <el-button color="#0eb394"  @click="addMember">添加会员</el-button>
        <el-button type="info"   @click="batchExport">批量导入</el-button>
        <el-button type="info"  @click="batchBindCard">批量绑卡</el-button>
      </el-button-group>
    </div>
    <el-divider></el-divider>
    <el-table :data="tableData.list" style="width: 100%" >
      <el-table-column prop="name" label="会员姓名(手机号)" width="180"  />
      <el-table-column prop="sex" label="性别" width="180" />
      <!--      后端返回了整张卡，实际上只需要一张-->
      <!--      <el-table-column prop="memberCards" label="会员卡" >-->
      <!--        <template #default="scope">-->
      <!--        <span v-if="scope.row.memberCards && scope.row.memberCards.length">-->
      <!--          {{ scope.row.memberCards.map(card => card.name).join(', ') }}-->
      <!--        </span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->

      <el-table-column prop="memberCards" label="会员卡">
        <template #default="scope">
      <span v-if="scope.row.memberCards && Array.isArray(scope.row.memberCards)">
        <!-- 使用过滤器排除 null 值 -->
        {{ scope.row.memberCards.filter(card => card !== null).map(card => card.name).join(', ') }}
      </span>
          <span v-else>
        无会员卡
      </span>
        </template>
      </el-table-column>
      <el-table-column prop="birthDay" label="入会日期" />
      <el-table-column prop="note" label="备注" />
      <el-table-column  label="操作"  width="250">
        <template #default="scope">
          <el-button-group >
            <el-button type="primary" >编辑</el-button>
            <el-button type="success" @click="viewDetails(scope.row.id)">详情</el-button>
            <el-button @click="deleteMember(scope.row.id)" type="danger">注销会员</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <el-divider></el-divider>
    <el-row>
      <el-col :span="20">
        <el-pagination  v-model:current-page="pageData.pageCurrent"
                        :page-size="pageData.pageSize"
                        layout="prev, pager, next"
                        :total="pageData.pageTotal"
                        prev-text="上一页"
                        next-text="下一页"
                        @current-change="handleCurrentChange" />
      </el-col>
      <el-col :span="4" style="font-size: 14px;">
        <span>当前 {{(pageData.pageCurrent-1)*pageData.pageSize+1}} 条到 {{ pageData.pageSize*pageData.pageCurrent }} 条 共 {{pageData.pageTotal}} 条</span>  </el-col>
    </el-row>

    <!-- 添加会员的抽屉 -->
    <el-drawer v-model="drawer" title="添加会员" :direction="direction" size="50%">
      <!-- <el-steps style="max-width: 600px" :active="active" finish-status="success" simple> -->
      <div  style="width: 100%; height: 120px;text-align: center;">
        <el-steps style="max-width: 600px" :active="active" finish-status="success" simple>
          <el-step title="会员信息" />
          <el-step title="绑定会员卡" />
          <el-step title="完成" />
        </el-steps>
      </div>
      <div style=" text-align: center; width: 90%; margin-left: 20px;">
        <el-form
            :model="form"
            :label-width="80"
            status-icon
            v-if="active==1"
        >

          <!-- 会员姓名 -->
          <el-form-item label="会员姓名">
            <el-input v-model="form.name" placeholder="会员姓名"/>
          </el-form-item>

          <!-- 手机号 -->
          <el-form-item label="手机号">
            <el-input v-model="form.phone" placeholder="手机号"/>
          </el-form-item>

          <!-- 性别 -->
          <el-form-item label="性别">
            <el-radio v-model="form.sex" label="男" size="large">男</el-radio>
            <el-radio v-model="form.sex" label="女" size="large">女</el-radio>
            <el-radio v-model="form.sex" label="多元性别者" size="large">多元性别者</el-radio>
          </el-form-item>

          <!-- 出生日期 -->
          <el-form-item label="出生日期">
            <el-date-picker
                v-model="form.birthday"
                type="date"
                placeholder="yyyy-mm-dd"
                style="width: 100%"
            />
          </el-form-item>

          <!-- 备注 -->
          <el-form-item label="备注">
            <el-input v-model="form.note" type="textarea" placeholder="备注信息" />
          </el-form-item>

          <el-form-item>
            <el-button @click="onClick">保存,为该会员绑定会员卡</el-button>
            <el-button @click="onClick2">保存会员信息，暂不绑定会员卡</el-button>
            <el-button @click="cancelForm">取消</el-button>
          </el-form-item>
        </el-form   >
        <!-- 绑定会员卡的表单 -->
        <el-form
            :model="cardForm"
            :label-width="100"
            status-icon
            v-else-if="active == 2"
        >
          <el-form-item label="会员卡选择" >
            <el-select
                v-model="cardForm.id"
                placeholder="-请选择绑定的会员卡-"
                size="large"
                style="width: 100%"
            >
              <el-option
                  v-for="item in selectList.cardList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="重置次数" >
            <el-input-number
                v-model="cardForm.totalCount"
                :min="1"
                controls-position="right"
                class="w50"
            />
          </el-form-item>
          <el-form-item label="有效期" >
            <el-input-number
                v-model="cardForm.totalDay"
                :min="1"
                controls-position="right"
                class="w50"
            />
          </el-form-item>
          <el-form-item label="实收金额"  >
            <el-input  placeholder="金额" class="w50" v-model="cardForm.price">
              <template #prepend>
                <span>￥</span>
              </template>
              <template #append>
                <span>元</span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="选择支付方式"  v-model="cardForm.payMode">
            <el-select
                v-model="cardForm.payMode"
                placeholder="-请选择支付方式-"
                size="large"
                style="width: 100%"
            >
              <el-option
                  v-for="item in selectList.payModeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" >
            <el-input v-model="cardForm.note" type="textarea"  />
          </el-form-item>
          <el-form-item>
            <el-button type="danger"  @click="bindConfirm">确认</el-button>
            <el-button @click="cancelForm">取消</el-button>
          </el-form-item>
        </el-form>

        <div style="color:#676A6C; background-color: #eee;font-size: 45px; height: 120px;
                 text-align: center; padding: 20px auto;"  v-else>
          <span  style="line-height: 120px;">会员注册完成</span>
        </div>
      </div>
    </el-drawer>

    <!-- 会员详情抽屉 -->
    <el-drawer v-model="detailDrawer" title="会员详情" :direction="direction" size="50%">
      <div v-if="memberDetails.id">
        <el-form :model="memberDetails" :label-width="80">
          <el-form-item label="会员姓名">
            <el-input v-model="memberDetails.name" readonly />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="memberDetails.phone" readonly />
          </el-form-item>
          <el-form-item label="性别">
            <el-input :value="memberDetails.sex" readonly />
          </el-form-item>
          <el-form-item label="出生日期">
            <el-input v-model="memberDetails.birthday" readonly />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="memberDetails.note" type="textarea" readonly />
          </el-form-item>
          <!--          todo：会员卡显示-->
        </el-form>
      </div>
      <el-button @click="detailDrawer = false">关闭</el-button>
    </el-drawer>

  </div>

</template>

<script setup>
import {ref,reactive,onMounted,computed} from 'vue'
import { ElDrawer, ElMessageBox } from 'element-plus'
import axios from "axios";
const pageData = reactive({
  pageCurrent:1,
  pageSize:10,
  pageTotal:50
})
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  pageData.pageCurrent = val
  fetchMembers(); // 页码变化时重新获取数据
}

const tableData = ref({
  list: []
});
const baseUrl = import.meta.env.VITE_APP_BASE_URL; // 使用 import.meta.env 读取环境变量
const fetchMembers = async () => {
  try {
    const response = await axios.get(`${baseUrl}/member/list`, { // 不知道为什么只能硬编码


      //const response = await axios.get(`http://localhost:8080/member/list`, { // 发送GET请求到后端API
      params: {
        page: pageData.pageCurrent,
        size: pageData.pageSize
      }
    });
    const responseData = response.data.data;
    if (responseData && responseData.list) {
      // 更新表格数据
      tableData.value.list = responseData.list;

      // 更新分页数据
      //pageData.value.pageTotal = responseData.total;

      console.log('获取会员数据成功:', responseData.list);
    } else {
      console.error('获取会员数据失败: 数据格式不正确', response.data);
    }
  } catch (error) {
    console.error('获取会员数据失败:', error);
  }
}

// 在组件挂载时获取数据
onMounted(() => {
  fetchMembers();
});


/***添加会员 */
const addMember = ()=>{
  drawer.value=true //打开添加的抽屉
  active.value=1//  进度条
  console.log("添加会员")
}
/***批量导入 */
const batchExport = () => {

  console.log("批量导入")
}
/***批量绑卡 */
const batchBindCard = () => {

  console.log("批量绑卡")
}
//添加会员的抽屉
const formLabelWidth = '80px' //表单列表的宽度
let timer
const direction = ref('rtl') //抽屉的弹出方向
const drawer = ref(false)//添加抽屉的显示
const loading = ref(false)
const form = reactive({
  id: null,          // 对应 MemberDto 的 id
  name: '',          // 对应 MemberDto 的 name
  sex: '0',          // 对应 MemberDto 的 sex，默认为 '0'
  phone: '',         // 对应 MemberDto 的 phone
  birthday: '',      // 对应 MemberDto 的 birthday，格式为 'YYYY-MM-DD'
  note: '',          // 对应 MemberDto 的 note
  avatarUrl: '',     // 对应 MemberDto 的 avatarUrl
  isDeleted: 0,      // 对应 MemberDto 的 isDeleted，默认为 0
  createTime: '',    // 对应 MemberDto 的 createTime，格式为 'YYYY-MM-DD HH:mm:ss'
  lastModifyTime: '',// 对应 MemberDto 的 lastModifyTime，格式为 'YYYY-MM-DD HH:mm:ss'
  version: 1         // 对应 MemberDto 的 version，默认为 1
});



//保存按钮  保存 为会员绑定会员卡
const onClick = async () => {
  //会员和会员卡信息分别提交,所以这里提交会员信息
  try {
    if (active.value === 1) {

      drawer.value = true;              // 打开添加会员的抽屉
      active.value = 1;                 // 设置为第一步

      // 第一步：提交会员基本信息
      const response = await axios.post(`${baseUrl}/member/add`, form);
      if (response.data.message == "success") {
        // 成功后进入下一步绑定会员卡
        active.value = 2;

        // 保存会员ID用于绑定会员卡
        form.id = response.data.data;
        // console.log('id为:', form.id);
      } else {
        console.error('添加会员基本信息失败:', response.data.message);
      }
    } else {
      console.log("卡big了,不应该走到这里");
    }
  }
  catch (error) {
    console.error('添加会员基本信息失败:', error);
  }
}

//保存会员信息，暂时不绑定会员卡
//TODO:与onClick代码基本一致,可以复用
const onClick2 = async () => {
  try {
    if (active.value === 1) {
      // 第一步：提交会员基本信息
      const response = await axios.post(`${baseUrl}/member/add`, form);
      if (response.data.message == "success") {
        // 不绑定会员卡,直接跳转到成功界面
        active.value = 3;

        // 保存会员ID用于绑定会员卡
        form.id = response.data.data;
        // console.log('id为:', form.id);
      } else {
        console.error('添加会员基本信息失败:', response.data.message);
      }
    } else {
      console.log("卡big了,不应该走到这里");
    }
  }
  catch (error) {
    console.error('添加会员基本信息失败:', error);
  }

}

//绑定会员卡的数据
const cardForm = reactive({
  id: null,
  name: '',
  price: null,
  description: '',
  note: '',
  type: '',
  totalCount: 0,
  totalDay: 0,
  status: '0', // '0' 表示激活，'1' 表示非激活
  createTime: '', // 日期字符串
  lastModifyTime: '', // 日期字符串
  version: 1,
});
const selectList = reactive({
  cardList: [
    {
      value: '1',
      label: '测试卡',
    },
    {
      value: '2',
      label: '铜卡',
    },
    {
      value: '3',
      label: '金卡',
    },
  ],
  payModeList: [
    {
      value: '1',
      label: '支付宝',
    },
    {
      value: '2',
      label: '微信',
    },
    {
      value: '3',
      label: '现金',
    },
    {
      value: '4',
      label: '银行卡',
    },
  ],
})

//绑定会员卡确定
const bindConfirm = async () => {
// 生成要传送的JSON数据


  try {
    // 调用后端接口绑定会员卡

    const url = `http://localhost:8080/member/bindCard?memberId=${form.id}`;

    // 使用转换后的数据
    const response = await axios.post(url, cardForm);


    if (response.data.message === "success") {
      // 绑定成功
      ElMessageBox.alert('会员卡绑定成功', '成功', { confirmButtonText: '确定' });
      // 关闭抽屉
      drawer.value = false;
    } else {
      // 绑定失败
      ElMessageBox.alert('会员卡绑定失败: ' + response.data.message, '错误', { confirmButtonText: '确定' });
    }
  } catch (error) {
    // 网络请求失败
    ElMessageBox.alert('网络请求失败: ' + error.message, '错误', { confirmButtonText: '确定' });
  }
  active.value = 3
};


//取消按钮
const cancelForm = () => {
  drawer.value = false

}

//删除会员
const deleteMember = async (memberId) => {
  try {
    // 调用后端接口删除会员
    const response = await axios.post(`${baseUrl}/member/delete`, {id: memberId});
    if (response.data.message === "success") {
      // 删除成功
      ElMessageBox.alert('会员删除成功', '成功', { confirmButtonText: '确定' });
      // 关闭抽屉
      drawer.value = false;
      // 刷新显示数据
      fetchMembers();
    } else {
      // 删除失败
      ElMessageBox.alert('会员删除失败: ' + response.data.message, '错误', { confirmButtonText: '确定' });
    }
  } catch (error) {
    // 网络请求失败
    ElMessageBox.alert('网络请求失败: ' + error.message, '错误', { confirmButtonText: '确定' });
  }
};

const detailDrawer = ref(false);
const memberDetails = reactive({
  id: null,
  name: '',
  phone: '',
  sex: '',
  birthday: '',
  note: '',
});

const viewDetails = async (memberId) => {
  try {
    const response = await axios.get(`${baseUrl}/member/findById?id=${memberId}`);
    if (response.data.message === "success") {
      Object.assign(memberDetails, response.data.data);
      // 打印memberDetails
      console.log('获取会员详情成功:', memberDetails);
      detailDrawer.value = true;
    } else {
      console.error('获取会员详情失败:', response.data.message);
    }
  } catch (error) {
    console.error('获取会员详情失败:', error);
  }
};


//添加会步骤条
const  active = ref(0)
</script >

<style lang="less" scoped>
.handle-box {
  margin-bottom: 20px;
}
.handle-input {
  width: 220px;
}
.mr10 {
  margin-right: 10px;
}
.w50{
  width: 45%;
}
.el-button {
  margin-left: 0; /* 确保左侧没有额外的边距 */
  margin-right: 10px; /* 可以根据需要设置右侧的边距，或者保持一致 */
}


</style>